<template>
    <div>
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>{{ isaddOrOnt ? "添加文章" : "编辑文章" }}</span>
                </div>
            </template>
            <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="mdref" :rules="title">
                <el-form-item label="文章标题" prop='title'>
                    <el-input v-model="formInline.title" placeholder="文章标题" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="opendialog(mdref)">{{ isaddOrOnt ? "发布文章" : "编辑文章" }}</el-button>
                </el-form-item>
                <el-form-item>
                    <MdEditor v-model="text" @onUploadImg="onUploadImg" />
                </el-form-item>
            </el-form>
            <el-dialog v-model="dialogFormVisible" title="发布文章" append-to-body width="70%">
                <el-form :model="form" ref="ruleFormRef" :rules="rules">
                    <el-form-item label="文章标题" :label-width="formLabelWidth">
                        <span>{{ formInline.title }}</span>
                    </el-form-item>
                    <el-form-item label="文章描述" :label-width="formLabelWidth" prop="description">
                        <el-input v-model="form.description" :rows="2" type="textarea" placeholder="说点什么吧" show-word-limit
                            maxlength="30" resize='none' />
                    </el-form-item>
                    <el-form-item label="文章标签" :label-width="formLabelWidth" prop="lables">
                        <el-select v-model="form.lables" multiple placeholder="标签" style="width: 320px" clearable>
                            <el-option v-for="item in options" :key="item.id" :label="item.lable_name"
                                :value="item.lable_name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="文章缩略图" :label-width="formLabelWidth">
                        <upload :height="200" :width="200" :multiple="false" :limit="1" v-model:imglist="uploadimglist">
                        </upload>
                    </el-form-item>
                    <el-form-item label="是否置顶" :label-width="formLabelWidth">
                        <el-switch v-model="form.istotop" inline-prompt active-text="是" inactive-text="否"
                            :before-change="cantop" />
                    </el-form-item>
                    <el-form-item label="状态" :label-width="formLabelWidth" prop="option">
                        <el-radio-group v-model="form.option" class="ml-4">
                            <el-radio :label=1>公开</el-radio>
                            <el-radio :label=2>草稿箱</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="resetForm(ruleFormRef, mdref)">取消</el-button>
                        <el-button type="primary" @click="tosubmit(ruleFormRef)" v-if="isaddOrOnt">保存</el-button>
                        <el-button type="primary" @click="edmitarticle(ruleFormRef)" v-else>编辑</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>

import { Userstore } from "@/store/User.js"
import { validataArticleName, addarticle, submitFileName, getarticleByid, edmitarticleapi, editFileName, getAllowTotop } from "@/api/article.js"
import { getQiniuToken } from "@/api/users.js"
import { oneTimegetlables } from "@/api/lable.js"
import { useBaseStore } from "@/store/Base.js"
import { onMounted, reactive, ref, inject } from 'vue'
import { MdEditor } from 'md-editor-v3';
import { uploadqiniu } from "@/util/index.js"
import 'md-editor-v3/lib/style.css';
import upload from '@/components/upload.vue'
let reload = inject('reload')
import { useRoute, useRouter } from "vue-router"
const formLabelWidth = '140px'
let route = useRoute()
let router = useRouter()
let baseStore = useBaseStore()
let userstore = Userstore()
/* 表单的dom实例 */
let ruleFormRef = ref();
let mdref = ref();
let isaddOrOnt = ref(true)
let edmit_id = ref()
let iscantop = ref(true)
/* 分发数据 */
function deliverdata(data) {
    let {
        article_content,
        article_cover,
        article_description,
        article_istop,
        article_status,
        article_title,
        lables, id } = data
    formInline.title = article_title
    text.value = article_content
    form.description = article_description
    form.istotop = Boolean(article_istop)
    form.option = article_status
    form.lables = lables
    edmit_id.value = id
    uploadimglist.value = [
        {
            id: 1,
            url: article_cover,
            name: article_cover.split('/').pop(),
        }
    ]
}
/* 表单信息收集显示dialog */
const dialogFormVisible = ref(false)
let options = ref([
    {
        id: "1",
        lable_name: "css",
    },
])
/* 打开文章的选选项菜单 , 校验文章名字是否重复 */
const opendialog = async (mdref) => {
    await mdref.validate(async (valid, fields) => {
        if (valid) {
            if (!isaddOrOnt.value) {
                dialogFormVisible.value = true
            } else {
                /* 校验文章名字是否重复 */
                let res = await validataArticleName(formInline.title);
                if (res.data.status === 200) {
                    dialogFormVisible.value = true
                } else {
                    ElMessage({
                        message: '文章名字重复,请修改',
                        type: 'warning',
                    })
                }
            }

        } else {
            ElMessage({
                message: '请输入文章名字',
                type: 'warning',
            })
        }
    })
}
/* 图片的list */
let uploadimglist = ref([]);
/* 文章的状态选项 */
let form = reactive({
    description: "",
    istotop: false,
    lables: [],
    option: 1,
})
/* 文章的名字 */
const formInline = reactive({
    title: '',
})
/* 文章的内容 */
let text = ref("");
/* 文章状态选项的规则 */
const rules = reactive({
    description: {
        required: true,
        message: '请输入内容',
        trigger: 'blur'
    },
    lables: {
        required: true,
        message: '请选择标签',
        trigger: 'blur'
    },
    option: {
        required: true,
        message: '请选择',
        trigger: 'blur'
    }
})
const title = reactive({
    title: {
        required: true,
        message: '请输入标题',
        trigger: 'blur'
    }
})
onMounted(async () => {
    let res = await oneTimegetlables()
    if (res.data.status == 200) {
        options.value = res.data.data
    }
    /* 获取标签 */
    if (route.query?.id) {
        isaddOrOnt.value = false
        let id = route.query.id
        let res = await getarticleByid(id)
        if (res.data.status == 200) {
            /* 将文章的信息分送到各个模块 */
            deliverdata(res.data.data)
        }
    }
})
/* 重置表单 */
const resetForm = (formEl, mdref) => {
    if (!formEl || !mdref) return
    formEl.resetFields()
    mdref.resetFields()
}
async function cantop() {
    let res = await getAllowTotop()
    if (res.data.status == 200) {
        return true
    } else {
        ElMessage({
            message: '文章最多置顶两个',
            type: 'warning',
        })
        return false
    }
}
function resetF() {
    dialogFormVisible.value = false
    text.value = ''
    formInline.title = ""
    uploadimglist.value = []
    form.description = ""
    form.istotop = false
    form.lables = []
    form.option = 1
}
/* 整合参数 */
const IntegrationPrams = () => {
    /* 获取用户名 */
    if (userstore.isLogin) {
        /* 获取当前用户 */
        let username = userstore.userInfo.username
        return {
            code: 1,
            data: {
                article_title: formInline.title,
                article_author: username,
                article_content: text.value,
                article_description: form.description,
                article_istop: form.istotop,
                id: userstore.userInfo.id,
                lables: form.lables,
            }
        }
    } else {
        ElMessage({
            message: '请登录哦',
            type: 'warning',
        })
        return {
            code: 0,
            data: {}
        }

    }
}
/* 提交表单 */
async function tosubmit(formEl) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            /* 参数校验通过 获取七牛云的token */
            let data = await getQiniuToken();
            /* 获取七牛云的token成功 */
            if (data.data.status == 200) {
                baseStore.qiniuToken = data.data.data.uploadToken;
                let pramas = IntegrationPrams() /* 整合参数 */
                if (pramas.code) {
                    /* 有身份信息 提交文章信息*/
                    let res = await addarticle(pramas.data);
                    /* 拿到文章id */
                    if (res.data.status == 200) {
                        let article_id = res.data.data.article_id
                        let Checkuploadlist = await uploadqiniu(uploadimglist.value)
                        if (Checkuploadlist[0].status == 200) {
                            /* 上传文件成功 添加文件名字给后端*/
                            let ok = await submitFileName({
                                id: userstore.userInfo.id,
                                article_id,
                                file_name: import.meta.env.VITE_API_PHOTO + Checkuploadlist[0].data.key
                            })
                            if (ok.data.status == 200) {
                                ElMessage({
                                    message: '上传成功',
                                    type: 'success',
                                })
                                resetF()
                            }
                        }
                    }
                } else {
                    ElMessage({
                        message: '请登录',
                        type: 'warning',
                    })
                    /* 然后清空本地存储 , 跳转登录页 */
                }
            } else {
                /* 获取token不成功 */
                ElNotification({
                    title: 'Warning',
                    message: '上传失败',
                    type: 'warning',
                })
            }
        } else {
            ElMessage({
                message: '参数没对',
                type: 'warning',
            })
        }
    })
}
/* 修改文章 */
async function edmitarticle(formEl) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let uploadimglists = uploadimglist.value.filter(item => {
                if (item.raw && item.raw instanceof File) {
                    return item
                }
            })
            if (uploadimglists.length > 0) {
                /* 参数校验通过 获取七牛云的token */
                let data = await getQiniuToken();
                if (data.data.status == 200) {
                    baseStore.qiniuToken = data.data.data.uploadToken;
                    /* 获取七牛云的token成功 ,先上传七牛云*/
                    let Checkuploadlist = await uploadqiniu(uploadimglists)
                    if (Checkuploadlist[0].status == 200) {
                        /* 上传文件成功 添加文件名字给后端*/
                        let ok = await editFileName({
                            id: userstore.userInfo.id,
                            article_id: edmit_id.value,
                            file_name: import.meta.env.VITE_API_PHOTO + Checkuploadlist[0].data.key
                        })
                        if (ok.data.status == 200) {
                            ElMessage({
                                message: '上传成功',
                                type: 'success',
                            })

                        }
                    }
                }
            }
            let pramas = IntegrationPrams() /* 整合参数 */
            if (pramas.code) {
                /* 整合参数成功 */
                let res = await edmitarticleapi({
                    id: userstore.userInfo.id,
                    article_id: edmit_id.value,
                    data: pramas.data
                })
                if (res.data.status == 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    resetF()
                    router.push("/article")
                }
            }
        } else {
            ElMessage({
                message: '信息填写正确哦',
                type: 'warning',
            })
        }
    })
}

/* md的图片上传 */
const onUploadImg = async (files, callback) => {
    /* 参数校验通过 获取七牛云的token */
    let data = await getQiniuToken();
    if (data.data.status == 200) {
        baseStore.qiniuToken = data.data.data.uploadToken;
        const res = await Promise.all(
            files.map((file) => {
                return new Promise(async (rev, rej) => {
                    let result = await uploadqiniu(files)
                    console.log(result);
                    if (result[0].status === 200) {
                        const { key } = result[0].data
                        let filename = import.meta.env.VITE_API_PHOTO + key;
                        rev(filename)
                    } else {
                        rej("上传失败")
                    }
                });
            })
        );
        callback(res);
    }

}
</script>

<style lang="css" scoped>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

}

:deep(.el-card__header) {
    padding: 5px 10px !important;
}

.text {
    font-size: 14px;
}
</style>